<?php


namespace app\api\model;


use app\lib\exception\BaseException;
use think\Db;
use think\Model;
use think\Request;

class PlanModel extends Model
{
    protected $table = 'cash_plan';

    public static function getPlans($page = 1, $size = 10)
    {
        $query = self::
        where([])
            ->order('month', 'desc');
        return $query->paginate(
            $size, false, [
            'page' => $page
        ]);
    }

    public static function updatePlanRemark(Request $request)
    {
        $parmas = $request->post();
        $PlanModel = new PlanModel;
        $PlanModel->save([
            'remark' => $parmas['remark'],
        ], ['month' => $parmas['month']]);
    }

    public static function checkComplate($month, $state){
        if ($state == 4) {
            $books = Db::query("select * from cash_book where state = 1 and month = ? order by category asc, id asc", [$month]);
            $category_B = [];
            foreach ($books as $book) {
                if ($book['category'] == 'B') {
                    $category_B[] = $book['id'];
                }
            }
            if (count(InfoModel::getTotal($month, $category_B)['warning_fields']) != 0) {
                throw new BaseException([
                    'msg' => '检测到当前“计划明细表”，有未完成工作，无法转为“现金计划三”',
                    'code' => 9527,
                    'errorCode' => 400
                ]);
            }
        }
    }

    public static function updatePlanState($month, $state)
    {
        self::checkComplate($month, $state);
        $PlanModel = new PlanModel;
        if($state == 4){
            $PlanModel->save([
                'has_change' => 1,
                'state' => $state,
            ], ['month' => $month]);
        }else{
            $PlanModel->save([
                'state' => $state,
            ], ['month' => $month]);
        }

    }

}